package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName WmMaterialServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/13 22:10
 * @Version 1.0
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Resource
    private FileStorageService fileStorageService;
    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.endpoint}")
    String endpoint;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * @param multipartFile 上传的文件对象
     * @return 上传结果
     * @Description 上传图片
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        // 1. 参数校验
        if (ObjectUtils.isEmpty(multipartFile) || multipartFile.getSize() == 0) {
            CustomException.custom(AppHttpCodeEnum.PARAM_REQUIRE, "缺少文件对象参数");
        }
        // 2. 上传到oss
        String fileId;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = multipartFile.getOriginalFilename();
            String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(profix, filename + postfix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}", e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "上传错误！");
        }
        // 3. 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        // 4. 当前线程中获取用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (ObjectUtils.isEmpty(user)) {
            CustomException.custom(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 5.  保存素材信息并返回结果
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        wmMaterial.setUrl(webSite + fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1. 检查参数
        dto.checkParam();
        // 2. 判断是否登录
        Integer userId = WmThreadLocalUtils.getUser().getId();
        // 3. 封装查询数据
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if (dto.getIsCollection() != null && dto.getIsCollection().intValue() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        queryWrapper.eq(WmMaterial::getUserId, userId);
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 4. 执行查询并返回分页结果
        IPage<WmMaterial> pageResult = page(new Page(dto.getPage(), dto.getSize()), queryWrapper);
        // 为图片路径添加访问前缀
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        return PageResponseResult.page(dto.getPage(), dto.getSize(), pageResult.getTotal(), records);
    }

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        // 1. 检查参数
        if (ObjectUtils.isEmpty(id)) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据素材ID + 登录用户ID   查询素材信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getId())) {
            CustomException.custom(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        WmMaterial material = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId()));
        if (ObjectUtils.isEmpty(material)) {
            CustomException.custom(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 根据素材ID查询关联表中是否有引用  如果有:不能删除
        Integer relCount = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (relCount > 0) {
            CustomException.custom(AppHttpCodeEnum.DATA_EXIST, "该素材已经被引用，无法删除");
        }
        // 4. 删除素材  删除OSS中对应的素材
        removeById(id);
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 检查参数  type = 0 = 1
        if (ObjectUtils.isEmpty(id)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 登录用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getId())) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 修改操作
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId()));
        return ResponseResult.okResult();
    }
}
